package com.saunter.utils.encrypt;

import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.util.Date;
import java.util.Map;

@Component
@PropertySource(value = {"classpath:config/config.properties"}, encoding = "UTF-8")
public class JavaWebToken {
    @Resource
    private Environment environment;

    private static Environment static_environment;
    @PostConstruct
    public void init() {
        static_environment = this.environment;
    }
    public static Key getKeyInstance() {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        String str_create_key = static_environment.getProperty("encrypt_key");
        String encode_str = DatatypeConverter.printBase64Binary(str_create_key.getBytes());
        byte[] decode_str = DatatypeConverter.parseBase64Binary(encode_str);
        Key signingKey = new SecretKeySpec(decode_str, signatureAlgorithm.getJcaName());
        return signingKey;
    }

    public static String createJavaWebToken(String id, Map<String, Object> claims, long ttl_millis) {
        long now_millis = System.currentTimeMillis();
        Date now = new Date( now_millis);
        JwtBuilder jwtBuilder = Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS256, getKeyInstance())
                .setId(id)
                .setIssuedAt(now);
        if(ttl_millis >= 0) {
            Date exp = new Date(now_millis + ttl_millis);
            jwtBuilder.setExpiration(exp);
        }
        return jwtBuilder.compact();
    }

    public static String createJavaWebToken(String id, Map<String, Object> claims) {
        return createJavaWebToken(id, claims, -1);
    }

    public static Map<String, Object> parseJavaWebToken(String jwt) {
        if(null == jwt) return null;
        try {
            return Jwts.parser().setSigningKey(getKeyInstance()).parseClaimsJws(jwt).getBody();
        } catch (Exception e) {
            return null;
        }
    }

    public static Object parseJavaWebToken(String jwt, String key) {
        Map<String, Object> jwt_parse_res = parseJavaWebToken(jwt);
        return null != jwt_parse_res ? jwt_parse_res.get(key) : null;
    }
}
